package com.zsl.consumer.ctrl;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class LoadBalancerCtrl {
	/**
	 * 负载方式
	 */
	@Resource
	private LoadBalancerClient lb;

	@Resource
	private RestTemplate restTemplate;

	@Resource
	private EurekaClient eurekaDiscoveryClient;


	@GetMapping("/lb1")
	public String lb1() {

		// 具体服务
		//	List<InstanceInfo> instances = client2.getInstancesById("localhost:provider:7003");

		// 使用服务名 ，找列表
		List<InstanceInfo> instances = eurekaDiscoveryClient.getInstancesByVipAddress("provider", false);


//		for (InstanceInfo ins : instances) {
//			System.out.println(ToStringBuilder.reflectionToString(ins));
//		}

		if (instances.size() > 0) {
			// 服务
			for (InstanceInfo instanceInfo : instances) {
				if (instanceInfo.getStatus() == InstanceInfo.InstanceStatus.UP) {

					String url = "http://" + instanceInfo.getHostName() + ":" + instanceInfo.getPort() + "/test";

					System.out.println("url:" + url);

					RestTemplate restTemplate = new RestTemplate();
					String respStr = restTemplate.getForObject(url, String.class);

					System.out.println("respStr " + respStr);
				}
			}
		}
		return "lb1";
	}


	@GetMapping("/lb2")
	public String lb2() {

		// ribbon 完成客户端的负载均衡，过滤掉down了的节点
		ServiceInstance instance = lb.choose("provider");

		String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/test";

		RestTemplate restTemplate = new RestTemplate();

		String respStr = restTemplate.getForObject(url, String.class);
		System.out.println("url:" + url);
		System.out.println("respStr " + respStr);

		return "lb2";
	}

	@GetMapping("/lb3")
	public String lb3() {
		String url ="http://provider/test";
		String respStr = restTemplate.getForObject(url, String.class);
		return "lb3:" + respStr;
	}
}
